﻿using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ChatServer
{
	/*
	 * create listener pool - > port
	 * when client connect to server 
	*/

	/*
	 * User - 
	 * Recognize by IP client (Ip Client Name)
	 * Login / Logout
	 * List user available
	 * 
	*/

	public class Server
	{
		//properties
		Socket serverSocket = null;
		IPEndPoint ipServer = null;
		List<ServerInstance> lstServerInstance = null;

		public Server()
		{
			//Provides an IP address that indicates that the server must listen for client activity on all network interfaces.
			ipServer = new IPEndPoint(IPAddress.Any, 9999);
			serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

			lstServerInstance = new List<ServerInstance>();

			Init();
		}

		private void Init()
		{
			serverSocket.Bind(ipServer);
			serverSocket.Listen(10);

			/*
			 * Thread for each connect:
			 * When there is connect from client, we create object socket, create thread, and set parameter (obj socket) to thread
			 */
			while(true)
			{
				Socket client = serverSocket.Accept();
				ServerInstance newInstance = new ServerInstance( client);

				Thread newThread = new Thread(newInstance.CommunicateClient);
				newThread.Start();
			}
		}

		//create server instance and when connect, give it to server instance, make new

		protected void Close()
		{
			if (null != serverSocket) serverSocket.Close();
			while( lstServerInstance.Count > 0 )
			{
				
			}
		}
		//when server die
		//serverSocket.Close();


		public string OpenConnectionSocket()
		{
			byte[] bytes = new byte[256];
			string bResult = string.Empty;

			serverSocket.Bind(ipServer);
			serverSocket.Listen(10);
			System.Console.WriteLine("Server listenning...");

			ServerInstance instantServe = (ServerInstance) serverSocket.Accept();
			
			
			System.Console.WriteLine("Server accept...");

			instantServe.Send(Encoding.UTF8.GetBytes("Server: Hello"));
			System.Console.WriteLine("Server send data");

			instantServe.Receive(bytes);
			System.Console.WriteLine("Server receive data");

			instantServe.Close();

			bResult = Encoding.UTF8.GetString(bytes);
			System.Console.WriteLine("Server receive Result: " + bResult);

			return bResult;
		}


		//wait and connect
		//mutithread



	}
}
